import React, { useEffect, useState } from "react";
import { Modal, Form, Space, Select, Radio, Input, Row, Col, DatePicker, message } from "antd";
import { lineTypes, modalPropsType } from "@/constants/types";
import { useModel } from "@umijs/max";
import { isFba, isMixGroupType, isPostCode, isTogether } from "@/utils/dictUtil";
import { fetchDestinationOptions } from "../../services";
import { useComponentDidMount } from "@/hooks";
import { fetchLpsLineOptions } from "@/pages/ProductManage/services";
import XlSelect from "@/components/Form/XlSelect";
import dayjs from "dayjs";
import { fetchServiceProviderOptions } from "@/pages/BasicInfo/services";
import { useRequest } from "ahooks";

const {Item} = Form;
const rules = [{required: true}];
const labelCol = {span: 4}

const BookingModal = ({title, visible, onCancel, onSubmit, loading, currentRow}: modalPropsType) => {
  const [form] = Form.useForm();
  const { getDict } = useModel("dictModel");
  const cabinetTypes = getDict("cabinetType");
  const groupTypes = getDict("groupType");
  const boxTypes = getDict("boxType");
  const countrys = getDict("country");
  const destTypes = getDict("destType");
  const [destCodes, setDestCodes] = useState([]);

  const country = Form.useWatch('country', form);
  const destType = Form.useWatch('destType', form);
  const lineId = Form.useWatch('lineId', form);

  const [lines, setLines] = useState<lineTypes []>([]);
  const [shipList, setShipList] = useState([]);


  const groupType = Form.useWatch('groupType', form);

  const {data: peerSuppliers} = useRequest(async () => {
    const res = await fetchServiceProviderOptions({type: "peerSupplier"});
    return (res || []).map((v: any) => ({
      ...v,
      label: v.name,
      value: v.code
    }));
  });

  
  const handleSubmit = async () => {
    const res = await form.validateFields();
    if (!res?.cabinetCode && !res?.so) {
      message.warning('柜号和so必填一个');
      return;
    }
    onSubmit({
      ...res,
      peerSupplierName: peerSuppliers.find((v: any) => v.value === res?.peerSupplierId)?.label,
      businessTime: res?.businessTime ? res?.businessTime?.format('YYYY-MM-DD HH:mm:ss') : undefined,
      relatedOrderCodes: res?.relatedOrderCodes ? res?.relatedOrderCodes?.replace(/，/g, ',').replace(/\n/g, ',').split(',').filter(v => v.trim()) : undefined
    });
  }

  const shipChange = (val: string) => {
    const shipName = shipList?.find((v: {shipCode: string, shipName: string}) => v.shipCode === val)?.shipName;
    form.setFieldValue('shipName', shipName);
  }

  useEffect(() => {
    if (country && destType && isFba(destType)) {
      fetchDestinationOptions({destType, country}).then(
        res => {
          setDestCodes((res || []).map((v: string) => ({label: v, value: v})));
        }
      )
    } else {
      setDestCodes([]);
    }
  }, [country, destType]);


  useEffect(() => {
    if (lineId && lines?.length) {
      const list = lines?.find(v => v.id === lineId)?.shipList || [];
      setShipList(list);
    } else {
      setShipList([]);
    }
  }, [lineId, JSON.stringify(lines)])

  useComponentDidMount(() => {
    fetchLpsLineOptions().then(
      res => {
        setLines(res || []);
      }
    )
  });

  useEffect(() => {
    if (currentRow) {
      form.setFieldsValue({
        ...currentRow,
        businessTime: currentRow?.businessTime ? dayjs(currentRow.businessTime) : undefined,
        relatedOrderCodes: currentRow?.relatedOrderCodes?.length ? currentRow?.relatedOrderCodes?.join(',') : ''
      });
    }
  }, [JSON.stringify(currentRow)])

  return (
    <Modal
      title={title}
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      maskClosable={false}
      confirmLoading={loading}
      width="800px"
    >
      <Form form={form} className="modal-form-padding" labelCol={labelCol}>
        <Item label="装柜类型" required>
          <Space>
            <Item noStyle name="type" rules={[{required: true, message: '请选择装柜类型'}]}>
              <Select
                style={{width: "310px"}}
                options={cabinetTypes}
              />
            </Item>
            <Item noStyle name="groupType" rules={[{required: true, message: '请选择拼箱方式'}]}>
              <Select
                style={{width: "310px"}}
                options={groupTypes}
              />
            </Item>
          </Space>
        </Item>
        <Item label="柜子" name="virtualFlag" rules={rules}>
          <Radio.Group options={boxTypes} />
        </Item>
        <Item noStyle shouldUpdate={(prev, next) => prev.type !== next.type}>
          {({getFieldValue}) => {
            const type = getFieldValue('type');
            if (isTogether(type)) {
              return (
                <Item label="同行供应商" name="peerSupplierId" rules={rules}>
                  <XlSelect allowClear options={peerSuppliers} />
                </Item>
              );
            }
          }}
        </Item>
        {
          !isMixGroupType(groupType) && (
            <Item label="仓库点">
              <Space>
                <Item name="country" rules={[{required: true, message: '请选择国家'}]} noStyle>
                  <Select
                    style={{width: "202px"}}
                    options={countrys}
                  />
                </Item>
                <Item name="destType" rules={[{required: true, message: '目的的类型'}]} noStyle>
                  <Select
                    style={{width: "200px"}}
                    options={destTypes}
                  />
                </Item>
                <Item noStyle shouldUpdate={(prev, next) => (prev.country !== next.country || prev.destType !== next.destType)}>
                  {({getFieldValue}) => {
                    const destType = getFieldValue('destType');
                    if (isPostCode(destType)) {
                      return (
                        <Item name="destCode" rules={[{required: true, message: '请输入邮编'}]} noStyle>
                          <Input
                            style={{width: "210px"}}
                          />
                        </Item>
                      );
                    }
                    if (isFba(destType)) {
                      return (
                        <Item name="destCode" rules={[{required: true, message: '请选择目的地'}]} noStyle>
                          <Select
                            showSearch
                            style={{width: "210px"}}
                            options={destCodes}
                          />
                        </Item>
                      );
                    }
                  }}
                </Item>
              </Space>
            </Item>
          )
        }
        <Row>
          <Col span={12}>
            <Item name="cabinetCode" label="柜号" labelCol={{span: 8}}>
              <Input />
            </Item>
          </Col>
          <Col span={12}>
            <Item name="so" label="SO" labelCol={{span: 8}}>
              <Input />
            </Item>
          </Col>
        </Row>
        <Item name="businessTime" label="业务时间" rules={[{required: true, message: '请选择业务时间'}]}>
          <DatePicker style={{width: '630px'}} />
        </Item>
        <Item name="lineId" label="线路名称" rules={[{required: true, message: '请选择线路'}]}>
          <XlSelect options={lines} onChange={() => form.setFieldsValue({shipCode: '', shipName: ''})} dataLabel="name" dataValue="id" />
        </Item>
        <Row>
          <Col span={12}>
            <Item label="船司" name="shipCode" labelCol={{span: 8}}>
              <XlSelect options={shipList} onChange={shipChange} dataLabel="shipName" dataValue="shipCode" />
            </Item>
            <Item noStyle hidden name="shipName" labelCol={{span: 8}}>
              <Input />
            </Item>
          </Col>
          <Col span={12}>
            <Item label="航名航次" name="shipLineNo" labelCol={{span: 8}}>
              <Input />
            </Item>
          </Col>
        </Row>
        {
          !currentRow && (
            <Item name="relatedOrderCodes" label="关联订单">
              <Input.TextArea rows={3} />
            </Item>
          )
        }
      </Form>
    </Modal>
  );
}
export default BookingModal;